package com.cheetah.start.common.shoesImg;

import org.opencv.core.*;
import org.opencv.imgproc.Imgproc;

import java.util.ArrayList;
import java.util.List;

public class ContourBasedExtraction {

    /**
     * 通过轮廓分析精确提取鞋子区域
     */
    public static Mat extractShoeByContour(Mat image) {
        // 先去除背景
        Mat noBackground = BackgroundRemoval.preciseBackgroundRemoval(image);

        // 转为灰度图
        Mat gray = new Mat();
        Imgproc.cvtColor(noBackground, gray, Imgproc.COLOR_BGR2GRAY);

        // 二值化
        Mat binary = new Mat();
        Imgproc.threshold(gray, binary, 1, 255, Imgproc.THRESH_BINARY);

        // 查找轮廓
        List<MatOfPoint> contours = new ArrayList<>();
        Mat hierarchy = new Mat();
        Imgproc.findContours(binary, contours, hierarchy,
                Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE);

        // 找到最大的轮廓（鞋子）
        double maxArea = 0;
        MatOfPoint largestContour = null;
        for (MatOfPoint contour : contours) {
            double area = Imgproc.contourArea(contour);
            if (area > maxArea) {
                maxArea = area;
                largestContour = contour;
            }
        }

        // 创建精确掩码
        Mat preciseMask = Mat.zeros(binary.size(), CvType.CV_8UC1);
        if (largestContour != null) {
            List<MatOfPoint> contourList = new ArrayList<>();
            contourList.add(largestContour);
            Imgproc.fillPoly(preciseMask, contourList, new Scalar(255));
        }

        // 应用精确掩码
        Mat result = new Mat();
        Core.bitwise_and(image, image, result, preciseMask);

        return result;
    }
}
